package com.gyf.mybatis.sqlsession;

import com.gyf.mybatis.pojo.Configuration;
import com.gyf.mybatis.pojo.MappedStatement;
import com.gyf.mybatis.util.GenericTokenParser;
import com.gyf.mybatis.util.ParameterMapping;
import com.gyf.mybatis.util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement statement, Object... paras) throws Exception {

        Connection connection = configuration.getDataSource().getConnection();
        // 转换sql
        String sql = statement.getSql();

        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        String parameterType = statement.getParameterType();
        Class<?> parameterTypeCls = Class.forName(parameterType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterTypeCls.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object obj = declaredField.get(paras[0]);
            preparedStatement.setObject(i + 1, obj);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = statement.getResultType();
        Class<?> resultTypeCls = Class.forName(resultType);
        List<Object> resultList = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object resultObj = resultTypeCls.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                try {
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeCls);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(resultObj, value);
                } catch (Exception e) {

                }
            }
            resultList.add(resultObj);
        }
        return (List<T>) resultList;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        //解析出来的sql
        String parseSql = tokenParser.parse(sql);
        //#{}解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql();
        boundSql.setSqlText(parseSql);
        boundSql.setParameterMappings(parameterMappings);

        return boundSql;
    }
}
